﻿using ProjectStatic.Models;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;

namespace ProjectStatic.Services
{
    public class DatasDb<T> where T : BaseModel,new()
    {
        public List<T> GetDatas(string tableName = "")
        {
            T t = new T();

            string sql = string.Format("select * from {0}", tableName == "" ? t.GetTableName() : tableName);
            return QueryDatas(sql);
        }
        public List<T> QueryDatas(string queryStr)
        {
            string sql = queryStr;
            DataSet ds = DbHelperSQL.Query(sql);
            List<T> prjList = new List<T>();
            foreach (DataRow row in ds.Tables[0].Rows)
            {
                if (row != null)
                {
                    var prj = new T();
                    prj.FillPropertyWithDataRow(row);
                    prjList.Add(prj);
                }
            }
            return prjList;
        }
        public bool PutData(T t)
        {
            string sql = t.GenerateInsertSqlStr();
            DbHelperSQL.ExecuteSql(sql);
            return true;
        }

        public bool DeleteData(T t)
        {
            string sql = t.GenerateDeleteSqlStr();
            DbHelperSQL.ExecuteSql(sql);
            return true;
        }

        public bool PutData(List<T> tList)
        {
            List<string> strs = new List<string>();
            foreach (var p in tList)
            {
                string sql = p.GenerateInsertSqlStr();
                strs.Add(sql);
            }
            DbHelperSQL.ExecuteSqlTran(strs);
            return true;
        }

        public bool DeleteData(List<T> tList)
        {
            List<string> strs = new List<string>();
            foreach (var p in tList)
            {
                string sql = p.GenerateDeleteSqlStr();
                strs.Add(sql);
            }
            DbHelperSQL.ExecuteSqlTran(strs);
            return true;
        }
    }
}